package com.mjk.manager.task.type.normal;

import java.lang.reflect.Method;
import java.util.Objects;

import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.scheduled.DynamicScheduledModel;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.BeanUtils;
import com.mjk.common.util.ClassUtil;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.ReflectionUtils;
import com.mjk.manager.task.type.ITaskInvoker;
import org.springframework.stereotype.Component;

@Component
public class NormalTaskInvoker implements ITaskInvoker {

	@Override
	public void taskInvoker(DynamicScheduledModel model){
		try {
			Class clazz = Class.forName(model.getTaskInstance());
			Object instance = BeeSpringBean.getBean(clazz);
			if (instance != null) {
				Method m = ReflectionUtils.getMethod(instance.getClass(), model.getTaskMethod());
                if (m.getParameters().length > 0) {
                    Class<?> pClazz = ClassUtil.loadClass(Objects.requireNonNull(m).getParameters()[0].getParameterizedType().getTypeName());
                    Object paramter;
                    if (ObjectUtils.isEmpty(model.getTaskParams())) {
                        paramter = Objects.requireNonNull(pClazz).newInstance();
                    } else {
                        paramter = BeanUtils.mapToBeanIgnoreCase(GsonUtils.json2Map(model.getTaskParams()), pClazz);
                    }

                    m.invoke(instance, paramter);
                } else {
                    m.invoke(instance);
                }
			}
		} catch (Exception e) {
            BizLogger.error(e);
		}
	}
}
